package com.training.killerapp;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.training.killerapp.model.Page;
import com.training.killerapp.model.User;

public class ShowPageServlet extends AbstractKillerAppServlet
{
    protected void doGet( HttpServletRequest request, HttpServletResponse response )
        throws ServletException, IOException
    {
        KillerApp killerApp = retrieveKillerApp();
        try
        {
            Page page = killerApp.getPage( request.getParameter( "email" ) );

            if( page == null )
            {
                response.setContentType("text/html");
                PrintWriter out = response.getWriter();
                out.println( "<html><body>No such user page exists :(. Check the <a href=\"list\">list</a></body></html>" );

                return;
            }

            request.setAttribute( "isCurrentUser", isUser( request ) );
            request.setAttribute( "page", page );
            request.setAttribute( "friends", page.getOwner().getFriends() );

            RequestDispatcher dispatcher = request.getRequestDispatcher( "show.jsp" );
            dispatcher.forward( request, response );
        }
        finally
        {
            releaseKillerApp( killerApp );
        }
    }

    private Boolean isUser( HttpServletRequest request )
    {
        String email = request.getParameter( "email" );
        User currentUser = getCurrentUser( request );
        return ( currentUser != null && email.equals( currentUser.getEmail() ) ) ? Boolean.TRUE : Boolean.FALSE;
    }
}
